/**
 * Created by kedong on 2016/5/27.
 */
$(function () {
    // 初始化用户信息
    var activityId = YQ.getQueryString("activityId") || 142,
        mealTime = YQ.getQueryString("mealTime") || "周五（11：30-12：30；17：00-18：00）",
        userId = YQ.getQueryString("userId") || "2",
        name = YQ.getQueryString("name") || "刘武",
        mobile = YQ.getQueryString("mobile") || "18627106565";

    YQ.set("activityId", activityId);
    YQ.set("mealTime", mealTime);
    if (userId) {
        YQ.setUser({
            id: userId,
            name: name,
            mobile: mobile
        })
    }

    // 购物车图标点击事件
    $(".J_shopping_car_btn").on("tap", function (e) {
        if (!$(".shopping_car").hasClass("empty"))
            $(".shopping_car_pop").toggle();
    });
    /**
     * 减少按钮
     */
    $("body").on("tap", ".J_subtract", function () {
        if (!YQ.isEnabled(this)) {
            return false;
        }
        dataNumChange($(this).parent(), 1);
    });
    /**
     * 增加按钮
     */
    $("body").on("tap", ".J_add", function () {
        if (!YQ.isEnabled(this)) {
            return false;
        }
        dataNumChange($(this).parent(), 2);
    });
    var dataNumChange = function (context, type) {
        try {
            var J_count = $(context).find(".J_count"),
                J_subtract = $(context).find(".J_subtract"),
            // 购物车
                shopping_car_pop = $("#shopping_car_pop"),
            // 商品信息
                goods = $(context).data("goods"),
            // 购物车显示的总数
                shopping_car_count = Number($(".shopping_car .J_shopping_car_count").attr("data_count")),
            // 当前总价格
                shopping_car_amount = Number($(".shopping_car .J_shopping_car_amount").attr("data_amount")),
            // 当前数量
                data_num = Number($(J_count).attr("data_num")),
            // 总价
                newAmount,
            // 所有商品的总数
                newCount,
            // 当前操作的商品的数量
                newNum;

            switch (type) {
                // 减少
                case 1:
                    newNum = data_num - 1;
                    newCount = shopping_car_count - 1;
                    newAmount = shopping_car_amount - goods.price;
                    break;
                //增加
                case 2:
                    newNum = data_num + 1;
                    newCount = shopping_car_count + 1;
                    newAmount = shopping_car_amount + Number(goods.price);
                    break;
            }
            newNum = newNum < 0 ? 0 : newNum;
            // 购买的数量有变化
            if (newNum != data_num) {

                // 更新购物车数据
                YQ.car.updateBaseInfo({
                    totalPrice: newAmount
                });
                YQ.car.addOrUpdateOrders({
                    id: goods.id,
                    goodsId: goods.id,
                    name: goods.name,
                    amount: newNum,
                    price: goods.price
                });

                $(".J_action_" + goods.id).find(".J_count").attr("data_num", newNum).text(newNum);
                if (newNum == 0) {
                    $(".J_action_" + goods.id).find(".J_count").addClass("hidden");
                    $(".J_action_" + goods.id).find(".J_subtract").addClass("hidden");
                } else {
                    $(".J_action_" + goods.id).find(".J_count").removeClass("hidden");
                    $(".J_action_" + goods.id).find(".J_subtract").removeClass("hidden");
                }
                /* 更改购物车信息*/
                // 1、更改底部显示的数量
                $(".shopping_car .J_shopping_car_count").attr("data_count", newCount).text(newCount);
                if (newCount > 0) {
                    $(".shopping_car").removeClass("empty");
                    $(".J_buy").removeClass("disabled");
                } else {
                    $(".J_buy").addClass("disabled");
                    $(".shopping_car").addClass("empty");
                    $(".shopping_car_pop").hide();
                    YQ.car.clear();
                }

                // 2、更改底部显示的总价
                $(".shopping_car .J_shopping_car_amount").attr("data_amount", newAmount).text("¥ " + newAmount);

                // 3、更改点击购物车后显示的列表
                if (!YQ.isExistInCar(goods.id)) {
                    // 添加的商品不存在于购物车中
                    CarList.render(new Array(goods));
                } else {
                    // 存在于购物车中，只需更改数量即可
                    if (newNum == 0) {
                        $(".goods_" + goods.id).remove();
                        // 更新购物车数据
                        YQ.car.delete({
                            id: goods.id,
                            goodsId: goods.id,
                            name: goods.name,
                            amount: newNum,
                            price: goods.price
                        });
                    } else {
                        $(".goods_" + goods.id).find(".J_count").attr("data_num", newNum).text(newNum);
                    }
                }
            }
        } catch (e) {
            YQ.log.error(e);
        }
    };

    /**
     * 下单
     */
    $(".J_buy").tap(function () {
        if (!$(".shopping_car").hasClass("empty"))
            location.href = "buy.html";
    });

});

/**
 * 取消、确认弹出框
 */
(function ($) {
    var Pop = function (setting) {
        this.setting = {};
        $.extend(this.setting, setting);
        this.pop = $(".alert_popover");
        // 取消
        $(this.pop).find(".cancel").tap(function (e) {
            e.stopPropagation();
            if (YQ.isEnabled(e.target)) {
                return false;
            }
            YQ.log.debug(event);
            this.cancel()
        }.bind(this));
        // 确定
        $(this.pop).find(".confirm").tap(function (e) {
            e.stopPropagation();
            if (YQ.isEnabled(e.target)) {
                return false;
            }
            YQ.log.debug(event);
            this.confirm()
        }.bind(this));
    };

    Pop.prototype = {
        getSettings: function (setting) {
            $.extend(this.setting, setting);
        },
        cancel: function () {
            $(this.pop).hide();
            $.isFunction(this.setting.cancel) && this.setting.cancel();
        },
        confirm: function () {
            $(this.pop).hide();
            $.isFunction(this.setting.confirm) && this.setting.confirm();
        },
        alert: function () {
            $(this.pop).show();
        }
    };

    Pop.init = function (setting) {
        return new this(setting);
    };

    window["Pop"] = Pop;
})(Zepto);

/**
 * 生成购物车列表
 */
(function ($) {
    var CarList = function (goods) {
        this.goods = goods || [];
        this.template = $(".J_goods_list_item_template");
        this.cantainer = $(".J_goods_list_item_cantainer");

        if (goods.length > 0) {
            YQ.log.debug(goods);
            for (var i = 0, count = goods.length; i < count; i++) {
                this.renderList(goods[i]);
            }
        }
    };

    CarList.prototype = {
        renderList: function (goods) {
            var new_item = this.template.clone(),
                J_goods_price = $(new_item).find(".J_goods_price"),
                J_goods_name = $(new_item).find(".J_goods_name"),
                J_action = $(new_item).find(".J_action"),
                J_count = $(new_item).find(".J_count"),
            // 选中的数量
                count;

            $(new_item).removeClass("J_goods_list_item_template hidden").addClass("goods_" + goods.id);

            $(J_goods_price).attr("data_price", goods.price).text("¥ " + goods.price);
            $(J_goods_name).text("¥ " + goods.name);

            /**
             *  添加  "J_action_" + X 的class是为了在点击加号和减号做同步操作时能够 快速的准确选择到相应的元素
             *
             *  另：也作为用以判断某一个元素是否存在于购物车列表中的依据
             */
            $(J_action).addClass("J_action_" + goods.id).attr("data_goodsId", goods.id);
            $(J_action).data("goods", goods);

            count = $(".J_action_" + goods.id).find(".J_count").attr("data_num");
            $(J_count).attr("data_num", count).text(count);

            this.cantainer.append(new_item)
        }
    };

    CarList.render = function (goods) {
        if (goods) {
            new this(goods);
        }
    };

    window["CarList"] = CarList;
})(Zepto);
